﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;

namespace PerfectBuyMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (Session["carrito"] == null)
            {
                List<PerfectBuyData.CarritoArticulo> carrito = new List<PerfectBuyData.CarritoArticulo>();
                Session["carrito"] = carrito;
                Session.Timeout = 60;
            }

            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Articulos(String productCategory, List<PerfectBuyData.Articulo> listaArt)
        {
            List<PerfectBuyData.Articulo> listaArticulos = new List<PerfectBuyData.Articulo>();
            if (listaArt == null)
            {
                listaArticulos = obtenArticulos(productCategory);
            }
            else
            {
                listaArticulos = listaArt;
            }
            return View(listaArticulos);
        }

        public ActionResult DetalleArticulo(int idArticulo)
        {
            PerfectBuyData.perfectbuyEntities context = new PerfectBuyData.perfectbuyEntities();
            PerfectBuyData.Articulo articulo = null;
            articulo = context.Articulos.FirstOrDefault(u => u.id == idArticulo);

            return View(articulo);
        }

        public List<PerfectBuyData.Articulo> obtenArticulos(string productCategory)
        {
            PerfectBuyData.perfectbuyEntities context = new PerfectBuyData.perfectbuyEntities();
            if (productCategory.ToLower().Equals("todos"))
            {
                return context.Articulos.Where(u => u.cantidad > 0).ToList();
            }
            else
            {
                return context.Articulos.Where(u => u.categoria.ToLower() == productCategory.ToLower() && u.cantidad > 0).ToList();
            }
        }

        [HttpPost]
        public ActionResult Articulos()
        {
            string textoBuscar = Request.Params["textoBuscar"].ToString();

            PerfectBuyData.perfectbuyEntities context = new PerfectBuyData.perfectbuyEntities();
            List<PerfectBuyData.Articulo> listaCoincidencias = context.Articulos.Where(u => u.nombre.Contains(textoBuscar) || u.descripcion.Contains(textoBuscar)).ToList();

            return Articulos("busqueda", listaCoincidencias);
        }
    }
}